package my.yuan.ms.rediskafkams.service.impl;

import lombok.extern.slf4j.Slf4j;
import my.yuan.ms.rediskafkams.controller.vo.MsVO;
import my.yuan.ms.rediskafkams.mapper.OrderrMapper;
import my.yuan.ms.rediskafkams.pojo.Orderr;
import my.yuan.ms.rediskafkams.producer.KafkaProducer;
import my.yuan.ms.rediskafkams.service.MsService;
import my.yuan.ms.rediskafkams.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zzMh
 * @Description TODO
 */
@Service
@Slf4j
public class MsServiceImpl implements MsService {
    @Autowired
    StockService stockService;
    @Autowired
    OrderrMapper orderrMapper;
    @Autowired
    KafkaProducer kafkaProducer;


    @Override
    public boolean executeMs(MsVO msVO) {
        //redis减库存
        boolean redisMinusStockFlag = stockService.redisMinusStock(msVO.getCid());
        if (!redisMinusStockFlag) {
            return false;
        }
        //发送msVO到 kafka
        kafkaProducer.send(msVO);
        return true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Throwable.class)
    public void handleMsAndOrder(MsVO msVo) throws Exception {

        try {
            log.info("开始mysql入库生成订单");
            stockService.mysqlMinusStock(msVo.getCid());
            log.info("mysql扣减库存成功！");
            StringBuilder sb = new StringBuilder();
            sb.append(msVo.getUid()).append("||").append(msVo.getCid());
            Orderr order = new Orderr();
            order.setCommondityId(msVo.getCid());
            order.setUserId(msVo.getUid());
            order.setName(sb.toString());
            log.info("开始生成订单前");
            orderrMapper.insertSelective(order);
            log.info("订单生成成功！秒杀结束~");
        } catch (Throwable e) {
            log.error("生成订单失败");
            throw new Exception("生成订单失败");
        }

    }


}
